package cn.b.sky.mes.em.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.b.sky.mes.em.model.MaintainConfig;
import cn.b.sky.mes.em.model.MaintainConfigAttach;
import cn.b.sky.mes.em.model.condition.MaintainConfigCondition;
import cn.b.sky.mes.em.service.MaintainConfigService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import org.apache.commons.lang3.StringUtils;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;

@Controller
@RequestMapping(value = "/maintainConfig/*")
public class MaintainConfigController extends SecurityController {
  @Resource
  MaintainConfigService maintainConfigService;

  @RequestMapping("maintainConfigList")
  public String maintainConfigList(Model model, @ModelAttribute("condition") MaintainConfigCondition config,
      String navTabId) {
    config.setSiteCode(SecurityContextUtil.getSiteCode());
    if (StringUtils.isEmpty(config.getOrderField())) {
      config.setOrderField("createDateTime");
    }
    List<MaintainConfig> configList = maintainConfigService.selectMaintainConfigByCondition(config);
    int count = maintainConfigService.selectMaintainConfigCount(config);
    config.setData(configList);
    config.setTotalCount(count);
    model.addAttribute("page", config);
    model.addAttribute(NAVTABID, navTabId);
    return "em/maintainConfig/maintainConfig_list";
  }

  @RequestMapping("addMaintainConfig")
  public String addMaintainConfig(Model model, String navTabId, HttpServletRequest request) {
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("sessionid", request.getSession().getId());
    return "em/maintainConfig/maintainConfig_add";
  }

  @RequestMapping("modifyMaintainConfig")
  public String modifyMaintainConfig(Model model, String navTabId, String id, HttpServletRequest request) {

    String[] ids = id.split(";");
    MaintainConfig config = maintainConfigService.selectMaintainConfigByCode(getSiteCode(), ids[0], ids[1]);
    List<MaintainConfigAttach> files = maintainConfigService.selectMaintainConfigAttachList(getSiteCode(), ids[0],
        ids[1]);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("config", config);
    model.addAttribute("files", files);
    model.addAttribute("sessionid", request.getSession().getId());
    return "em/maintainConfig/maintainConfig_edit";
  }

  @RequestMapping("viewMaintainConfig")
  public String viewMaintainConfig(Model model, String navTabId, String id) {
    String[] ids = id.split(";");
    MaintainConfig config = maintainConfigService.selectMaintainConfigByCode(getSiteCode(), ids[0], ids[1]);
    List<MaintainConfigAttach> files = maintainConfigService.selectMaintainConfigAttachList(getSiteCode(), ids[0],
        ids[1]);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("config", config);
    model.addAttribute("files", files);
    return "em/maintainConfig/maintainConfig_view";
  }

  @RequestMapping("delConfigAttachment")
  @ResponseBody
  public DWZResult delConfigAttachment(String attachmentCode, String equipmentCode, String strategyCode, String id) {
    if (StringUtils.isEmpty(attachmentCode)) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), SystemConstant.PARAMETERNULL));
    }
    maintainConfigService.deleteMaintainConfigAttach(getSiteCode(), equipmentCode, strategyCode, attachmentCode, id);
    return ajaxDone(null);
  }

  @RequestMapping(value = "saveAttachment")
  public void saveAttachment(HttpServletRequest request, String equipmentCode, String strategyCode,
      HttpServletResponse response) {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
    Iterator iter = fileMap.entrySet().iterator();
    while (iter.hasNext()) {
      Entry entry = (Entry) iter.next();
      MultipartFile file = (MultipartFile) entry.getValue();
      MaintainConfigAttach maintainConfigAttach = new MaintainConfigAttach();
      maintainConfigAttach.setSiteCode(getSiteCode());
      maintainConfigAttach.setEquipmentCode(equipmentCode);
      maintainConfigAttach.setStrategyCode(strategyCode);
      maintainConfigService.insertMaintainConfigAttach(maintainConfigAttach, file);
    }

  }

  @RequestMapping("saveMaintainConfig")
  @ResponseBody
  public DWZResult saveMaintainConfig(Model model, String navTabId, MaintainConfig config, String id,
      HttpServletRequest request) {
    if (config == null) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }
    config.setSiteCode(getSiteCode());
    setCreateInfo(config);
    if (StringUtils.isEmpty(id)) {
      MaintainConfig c = maintainConfigService.selectMaintainConfigByCode(getSiteCode(), config.getEquipmentCode(),
          config.getStrategyCode());
      if (c != null) {
        return ajaxError("维护配置已存在！");
      }
      maintainConfigService.insertMaintainConfig(config);
      return dialogAjaxDone(
          getImeViewMessageI18n(null, "successfulOperation.M"),
          null, null, null, null);
    } else {
      maintainConfigService.updateMaintainConfig(config);
      return dialogAjaxDone(
          getImeViewMessageI18n(null, "successfulOperation.M"),
          null, null, null, null);

    }
  }

  @RequestMapping("deleteMaintainConfig")
  @ResponseBody
  public DWZResult deleteMaintainConfig(Model model, String navTabId, String id, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    if (StringUtils.isEmpty(ids)) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }
    String[] ress = ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(ress.length);
    boolean hasFail = false;
    for (String res : ress) {
      String[] s = res.split(";");
      BatchJobReport report = maintainConfigService.deleteMaintainConfig(getSiteCode(), s[0], s[1]);
      reports.add(report);
      if (!report.isSuccess()) {
        hasFail = true;
      }
    }
    if (!hasFail) {
      // 直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null,
          getImeViewMessageI18n(null, "successfulOperation.M"),
          null);
    } else {
      return batchjobAjaxDone(request, reports);
    }

  }
}
